package com.google.code.swingonfire.showcase.graphic.sketch;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

import com.google.code.swingonfire.plotter.Plotter;
import com.google.code.swingonfire.plotter.Sketch;
import com.google.code.swingonfire.showcase.utils.ParameterPanel;
import com.google.code.swingonfire.utility.Reflection;

public class SketchParameterPanel extends JPanel implements ActionListener
{

    private static final long serialVersionUID = -7470447908281571751L;

    private final SketchSample sample;
    private final PlotterComponent plotterComponent;
    private final ParameterPanel parameterPanel;

    public SketchParameterPanel(SketchSample sample, PlotterComponent plotterComponent)
    {
        super(new BorderLayout());

        setOpaque(true);
        setBackground(Color.WHITE);
        setBorder(BorderFactory.createEmptyBorder(8, 12, 8, 12));

        this.sample = sample;
        this.plotterComponent = plotterComponent;

        parameterPanel = new ParameterPanel(sample.getParameterDefinitions());
        parameterPanel.addActionListener(this);

        add(parameterPanel, BorderLayout.CENTER);
    }

    @Override
    public void actionPerformed(ActionEvent event)
    {
        updatePlotterComponent();
        plotterComponent.repaint();
    }

    public void updatePlotterComponent()
    {
        Object[] parameters = parameterPanel.getParameters();
        Constructor<? extends Sketch> constructor =
            Reflection.findConstructor(sample.getType(), Reflection.typesOf(parameters));

        try
        {
            plotterComponent.setPlotter(new Plotter(constructor.newInstance(parameters)));
        }
        catch (IllegalArgumentException e)
        {
            e.printStackTrace(System.err);
        }
        catch (InstantiationException e)
        {
            e.printStackTrace(System.err);
        }
        catch (IllegalAccessException e)
        {
            e.printStackTrace(System.err);
        }
        catch (InvocationTargetException e)
        {
            e.printStackTrace(System.err);
        }
    }
}
